package com.example.demo.controller;

import com.example.demo.util.CaptchaUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author 三石
 */
@RestController
@RequestMapping("/Captcha")
public class CaptchaController {

    @Resource
    private RedisTemplate<String, String> redisTemplate;


    @GetMapping("/getCaptcha")
    protected void service(HttpServletResponse resp) throws IOException {
        // 获取验证码
        String code = CaptchaUtil.generateCode();
        BufferedImage image = CaptchaUtil.generateImage(code);

        // 将验证码存入Redis
        code = code.toLowerCase();
        redisTemplate.opsForValue().set("captcha", code);
        //有效期5分钟
        redisTemplate.expire("captcha",5, TimeUnit.MINUTES);
        System.out.println(redisTemplate.opsForValue().get("captcha"));

        // 禁止图像缓存
        resp.setHeader("Pragma", "no-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0);
        resp.setContentType("image/jpeg");

        // 将图像输出到Servlet输出流中
        ServletOutputStream out = resp.getOutputStream();
        ImageIO.write(image, "jpeg", out);
        out.close();
    }
}